package com.hitalkie.teacher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hitalkie.teacher.R;
import com.hitalkie.teacher.app.TalkieApi;
import com.hitalkie.teacher.app.TalkieApplication;
import com.hitalkie.teacher.fragment.LoadingDialogFragment;
import com.hitalkie.teacher.model.BaseResponse;
import com.hitalkie.teacher.model.Country;
import com.hitalkie.teacher.model.ResponseStatus;
import com.hitalkie.teacher.model.User;
import com.hitalkie.teacher.tx.Constants;
import com.hitalkie.teacher.tx.MySelfInfo;
import com.hitalkie.teacher.tx.QavsdkControl;
import com.hitalkie.teacher.util.OkHttpManager;
import com.tencent.TIMCallBack;
import com.tencent.TIMManager;
import com.tencent.TIMUser;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.common.inter.ITagManager;
import com.umeng.message.tag.TagManager;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Date 25/09/2016
 *
 * @author charliema
 */

public class SignUpActivity extends BaseActivity {

    private final static int REQ_CODE_COUNTRY = 0;

    private boolean mIsEtPhoneEmpty = true;
    private boolean mIsEtPasswordEmpty = true;
    private boolean mIsSMSCodeEmpty = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == REQ_CODE_COUNTRY) {
            Country country = (Country) data.getSerializableExtra(CountryListActivity.EXTRA_COUNTRY);
            ((TextView) findViewById(R.id.tvPhoneRegionCode)).setText(country.area_code);
        }

    }

    private void initView() {
        setContentView(R.layout.view_sign_up);
        initTitleBar();

        findViewById(R.id.tvPhoneRegionCode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent().setClass(getActivity(), CountryListActivity.class), REQ_CODE_COUNTRY);
            }
        });
        findViewById(R.id.tvSmsCodeRequest).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (findViewById(R.id.tvSmsCodeRequest).isEnabled()) {
                    requestSmsCode();
                }
            }
        });

        findViewById(R.id.tvConfirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signUp();
            }
        });

        findViewById(R.id.tvSignIn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), SignInActivity.class));
            }
        });

        EditText etPhone = (EditText) findViewById(R.id.etPhone);
        final EditText etPassword = (EditText) findViewById(R.id.etPassword);
        EditText etSMSCode = (EditText) findViewById(R.id.etSmsCode);
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mIsEtPhoneEmpty = TextUtils.isEmpty(s.toString());
                checkFormEnable();
                checkPhoneFormEnable();
            }
        });
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mIsEtPasswordEmpty = TextUtils.isEmpty(s.toString());
                checkFormEnable();
            }
        });
        etSMSCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mIsSMSCodeEmpty = TextUtils.isEmpty(s.toString());
                checkFormEnable();
            }
        });

        ((CheckBox) findViewById(R.id.cbEye)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
    }

    private void initTitleBar() {
        findViewById(R.id.viewTitleBarLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

    }

    private void checkPhoneFormEnable() {
        if (mIsEtPhoneEmpty) {
            findViewById(R.id.tvSmsCodeRequest).setEnabled(false);
        } else {
            findViewById(R.id.tvSmsCodeRequest).setEnabled(true);
        }
    }

    private void requestSmsCode() {
        EditText etPhone = (EditText) findViewById(R.id.etPhone);
        TextView tvRegionCode = (TextView) findViewById(R.id.tvPhoneRegionCode);
        String phone = etPhone.getText().toString();
        String regionCode = tvRegionCode.getText().toString();
        requestSmsCode(regionCode + phone);

    }

    private void requestSmsCode(String phone) {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        // assemble data
        Map<String, String> data = new HashMap<>();
        data.put("phone", phone);
        data.put("usage", "signup");

        OkHttpManager.client.newCall(
                new Request.Builder().url(TalkieApi.getHost() + TalkieApi.PATH_REQUEST_SMS_CODE)
                        //
                        .post(RequestBody.create(OkHttpManager.JSON, new Gson().toJson(data)))
                        .build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                Toast.makeText(getActivity(), getText(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        Log.e(TAG, "requestSmsCode  resp:" + jsonStr);

                        try {
                            final BaseResponse resp = new Gson().fromJson(jsonStr, BaseResponse.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {

                                    if (resp.status.error_code == 0) {
                                        onRequestSmsCodeSuccess(resp);
                                    } else {
                                        onRequestSmsCodeFailure(resp);
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                }
                            });
                        }
                    }
                });

    }


    private void checkFormEnable() {
        if (mIsEtPhoneEmpty || mIsEtPasswordEmpty || mIsSMSCodeEmpty) {
            findViewById(R.id.tvConfirm).setEnabled(false);
        } else {
            findViewById(R.id.tvConfirm).setEnabled(true);
        }
    }

    private void signUp() {
        EditText etPhone = (EditText) findViewById(R.id.etPhone);
        EditText etPassword = (EditText) findViewById(R.id.etPassword);
        EditText etSMSCode = (EditText) findViewById(R.id.etSmsCode);
        EditText etInviteCode = (EditText) findViewById(R.id.etInviteCode);
        TextView tvRegionCode = (TextView) findViewById(R.id.tvPhoneRegionCode);

        String phone = etPhone.getText().toString();
        String password = etPassword.getText().toString();
        String smsCode = etSMSCode.getText().toString();
        String inviteCode = etInviteCode.getText().toString();
        String regionCode = tvRegionCode.getText().toString();

        signUp(regionCode + phone, password, smsCode, inviteCode);
    }

    private void signUp(String phone, String password, String smsCode, String inviteCode) {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        // assemble data
        Map<String, String> data = new HashMap<>();
        data.put("phone", phone);
        data.put("password", password);
        data.put("code", smsCode);
        data.put("invitation", inviteCode);

        OkHttpManager.client.newCall(
                new Request.Builder().url(TalkieApi.getHost() + TalkieApi.PATH_SIGN_UP)
                        //
                        .post(RequestBody.create(OkHttpManager.JSON, new Gson().toJson(data)))
                        .build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), getText(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        Log.e(TAG, "sign in  resp:" + jsonStr);

                        try {
                            final SignUpResp resp = new Gson().fromJson(jsonStr, SignUpResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                    if (resp.status.error_code == 0) {
                                        imLogin(resp.user.token, resp.user.id, resp.user.type, resp.user.im_user_id, resp.user.tc_user_sign);
                                    } else {
                                        onSignInFailure(resp);
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    private void onRequestSmsCodeSuccess(BaseResponse resp) {
        // 倒计时 和 可用状态
        final TextView tv = (TextView) findViewById(R.id.tvSmsCodeRequest);
        tv.setEnabled(false);
        new CountDownTimer(20000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv.setText("" + (millisUntilFinished / 1000) + " seconds remaining");
            }

            @Override
            public void onFinish() {
                tv.setText(getText(R.string.request_sms_code));
                tv.setEnabled(true);
            }
        }.start();

    }

    private void onRequestSmsCodeFailure(BaseResponse resp) {
        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
    }


    private void onSignInFailure(SignUpResp resp) {
        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
    }

    private static class SignUpResp extends BaseResponse {
        User user;
    }

    public void imLogin(final String token, final long userId, final int userType, final String identify, final String userSig) {
        TIMUser user = new TIMUser();
        user.setAccountType(String.valueOf(Constants.ACCOUNT_TYPE));
        user.setAppIdAt3rd(String.valueOf(Constants.SDK_APPID));
        user.setIdentifier(identify);
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");
        //发起登录请求
        TIMManager.getInstance().login(
                Constants.SDK_APPID,
                user,
                userSig,
                new TIMCallBack() {
                    @Override
                    public void onError(int i, String s) {
                        Log.e(TAG, "IMLogin fail ：" + i + " msg " + s);
//                        Toast.makeText(getActivity(), "IMLogin fail ：" + i + " msg " + s, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess() {
                        Log.i(TAG, "keypath IMLogin succ !");
//                        Toast.makeText(mContext, "IMLogin succ !", Toast.LENGTH_SHORT).show();
                        loadingDialogFragment.dismiss();
                        TalkieApplication.signIn(token, userId, userType);

                        MySelfInfo.getInstance().setId(identify);
                        MySelfInfo.getInstance().setUserSig(userSig);
                        MySelfInfo.getInstance().writeToCache(getApplicationContext());

                        startAVSDK();

                        bindPush(userId, userType);
                    }
                });
    }

    private void startAVSDK() {
        QavsdkControl.getInstance().setAvConfig(Constants.SDK_APPID, "" + Constants.ACCOUNT_TYPE, MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());
        QavsdkControl.getInstance().startContext();
//        if (mLoginView != null)
//            mLoginView.loginSucc();
    }

    private void bindPush(final long userId, final int userType) {
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");
        PushAgent.getInstance(getApplicationContext()).addAlias("" + userId, "NONE", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean isSuccess, String s) {
                if (isSuccess) {
                    // 先清空tag
                    PushAgent.getInstance(getApplicationContext()).getTagManager().reset(new TagManager.TCallBack() {
                        @Override
                        public void onMessage(boolean b, ITagManager.Result result) {
                            Log.e(TAG, "unbind push tag:" + b + "   " + result);

                        }
                    });
                    // 绑定tag
                    PushAgent.getInstance(getApplicationContext()).getTagManager().add(new TagManager.TCallBack() {
                        @Override
                        public void onMessage(boolean isSuccess, ITagManager.Result result) {
                            if (isSuccess) {
                                loadingDialogFragment.dismiss();
                                MobclickAgent.onProfileSignIn("" + userId);
                                navigateToMain();
                            } else {
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
//                                        Toast.makeText(getActivity(), "登录失败：无法绑定推送Tag", Toast.LENGTH_LONG).show();
                                        loadingDialogFragment.dismiss();
                                        Log.e(TAG, "sign in fail: can not bind push tag");
                                    }
                                });
                            }
                        }
                    }, "" + userType);
                } else {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
//                            Toast.makeText(getActivity(), "登录失败：无法绑定推送Alias", Toast.LENGTH_LONG).show();
                            loadingDialogFragment.dismiss();
                            Log.e(TAG, "sign in fail: can not bind push alias");
                        }
                    });
                }
            }
        });
    }


    private void navigateToMain() {
        Intent i = new Intent(getActivity(), MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(i);
        getActivity().finish();
    }
}
